package com.moseph.qrsqueeze;

import java.awt.BorderLayout;
import java.awt.image.BufferedImage;
import java.util.*;

import javax.swing.JFrame;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;

import processing.core.*;
import processing.video.Capture;

public class QRReader extends PApplet
{
	Capture cam;
	static int imgWidth = 640;
	static int imgHeight = 480;
	String cameraName = "USB Video Class Video";
	Reader reader = new QRCodeReader();

	int WIDTH = 640;
	int HEIGHT = 480;

	PImage cover;  //This will have the cover image
	String lastISBNAcquired = "";  //This is the last ISBN we acquired
	boolean drawImage;
	boolean drawPoints;

	public static void main( String[] args )
	{
		JFrame f = new JFrame( "QR SqueezePlayer Capture" );
		f.setLayout( new BorderLayout() );
		QRReader reader = new QRReader();
		f.add( reader );
		reader.init();
		f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
		f.setSize( imgWidth, imgHeight );
		f.setVisible( true );
	}

	public void setup()
	{
		super.setup();
		size( imgWidth, imgHeight );
		List<String> cameraNames = new ArrayList<String>();
		cameraNames.addAll( Arrays.asList( Capture.list() ) );
		println( Capture.list() );
		startCamera();
	}

	public void draw()
	{
		if( cam.available() == true )
		{
			cam.read();
			if( drawImage ) image( cam, 0, 0 );
			try
			{
				// Now test to see if it has a QR code embedded in it
				LuminanceSource source = new BufferedImageLuminanceSource( (BufferedImage) cam.getImage() );
				BinaryBitmap bitmap = new BinaryBitmap( new HybridBinarizer( source ) );
				Result result = reader.decode( bitmap ); //Once we get the results, we can do some display 
				if( result.getText() != null && drawPoints ) //Draw some ellipses on at the control points 
				{
					fill(255f, 0, 0);
					for ( ResultPoint p : result.getResultPoints() ) ellipse( p.getX(), p.getY(), 20, 20 );
				}
				processResult( result );
			} catch (NotFoundException e) { notFound(); } 
			catch (ChecksumException e) { badChecksum(); }
			catch (Exception e) { println(e.toString());e.printStackTrace(); }
		}
	}
	
	public void processResult( Result result ) { 	}
	public void notFound() { 	}
	public void badChecksum() { }

	public void startCamera()
	{
		if( cam != null )
		{
			cam.stop();
			cam.dispose();
		}
		try
		{
			cam = new Capture( this, imgWidth, imgHeight, cameraName, 10 );
		} catch (Exception e)
		{
			System.err.println( "Couldn't open camera " + cameraName + ": " + e.getMessage() );
			e.printStackTrace();
			return;
		}
	}
}
